/*
 *   Copyright 2012, Thomas Kerber
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package milk.jpatch.fileLevel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import milk.jpatch.Util;

/**
 * Patch denoting that a file was replaced.
 * @author Thomas Kerber
 * @version 1.0.1
 */
public class FileReplace extends FilePatch{
    
    /**
     * The file to replace with.
     */
    private final File f;
    
    /**
     * Creates.
     * @param dir The root from which to find the new file.
     * @param name The filename.
     * @throws FileNotFoundException
     */
    public FileReplace(File dir, String name) throws FileNotFoundException{
        super(name);
        f = new File(dir, name);
    }
    
    /**
     * 
     * @return The file to replace with.
     */
    public File getFile(){
        return f;
    }
    
    @Override
    public void patch(InputStream in, OutputStream out) throws IOException{
        if(in != null)
            in.close();
        in = new FileInputStream(f);
        Util.loop(in, out);
    }
    
    @Override
    public void serialize(File dir) throws IOException{
        File outF = new File(dir, name);
        outF.getParentFile().mkdirs();
        InputStream in = new FileInputStream(f);
        OutputStream out = new FileOutputStream(outF);
        Util.loop(in, out);
    }
    
    /**
     * 
     * @param f A file.
     * @return Whether the file can be deserialized or not.
     */
    public static boolean canDeserializeAt(File f){
        return f.isFile();
    }
    
    /**
     * Deserializes a file in relation to a root directory.
     * @param root The root.
     * @param f The file.
     * @return The deserialization.
     * @throws FileNotFoundException
     */
    public static FileReplace deserializeAt(File root, File f)
            throws FileNotFoundException{
        String relPath = Util.getRelativePath(root, f);
        return new FileReplace(root, relPath);
    }
    
}
